import cv2
import json
import os.path as osp


class Kernels:
	KERNELS_STORE_PATH = 'KernelsConfig.json'

	def __init__(self):
		pass

	def getKernel(self, tag, getAll=False):
		if osp.exists(self.KERNELS_STORE_PATH):
			with open(self.KERNELS_STORE_PATH, 'r') as f:
				allKernelsJson = f.read()
			f.close()
			if allKernelsJson is not None:
				allKernelsPython = json.loads(allKernelsJson)
				if getAll:
					return allKernelsPython
				else:
					if tag in allKernelsPython and allKernelsPython[tag] is not None:
						shape = allKernelsPython[tag]['shape']
						size = allKernelsPython[tag]['size']
						kernel = cv2.getStructuringElement(shape, (size[0], size[1]))
						return kernel
					else:
						return None
		else:
			return {}

	def addKernel(self, tag, shape, size):
		kernel = {
			'shape': shape,
			'size': [size[0], size[1]]
		}
		existedKernels = self.getKernel(None, True)
		existedKernels[tag] = kernel
		kernelJson = json.dumps(existedKernels, indent=2)
		with open(self.KERNELS_STORE_PATH, 'w') as f:
			f.write(kernelJson)
		f.close()

	def quickKernel(self, tag):
		kernel = self.getKernel(tag)
		if kernel is not None:
			return kernel
		w = None
		h = None
		r = tag.find('r')
		c = tag.find('c')
		e = tag.find('e')
		shape = None
		for i, m in enumerate([r, c, e]):
			if m != -1:
				w = tag[0:m]
				h = tag[m+1:]
				shape = i
		if w.isdigit() and h.isdigit():
			self.addKernel(tag, shape, (int(w), int(h)))
			return self.getKernel(tag)
		return None


if __name__ == '__main__':
	kernels = Kernels()
	k = kernels.quickKernel('5c3')
	print(k)
